<template>
  <BubbleMenu
    v-if="editor && shouldShow"
    :editor="editor"
    :options="bubbleMenuOptions"
    :should-show="shouldShowMenu"
  >
    <div class="bubble-menu-container" @mousedown.stop>
      <slot />
    </div>
  </BubbleMenu>
</template>

<script setup lang="ts">
import { computed, inject, type Ref } from "vue";
import { BubbleMenu } from "@tiptap/vue-3/menus";
import type { Editor } from "@tiptap/vue-3";

defineOptions({
  name: "BubbleMenuContainer",
});

interface BubbleMenuContainerProps {
  /**
   * 判断是否应该显示菜单的函数
   */
  shouldShow?: (props: any) => boolean;
  /**
   * BubbleMenu 的选项配置
   */
  options?: any;
}

const props = withDefaults(defineProps<BubbleMenuContainerProps>(), {
  shouldShow: undefined,
  options: () => ({
    placement: "top",
    offset: 8,
  }),
});

const editor = inject<Ref<Editor | null>>("editor");
const documentOptions = inject<Ref<any>>("document");

// 是否应该显示气泡菜单
const shouldShow = computed(() => {
  return documentOptions?.value?.enableBubbleMenu ?? true;
});

// 合并默认选项
const bubbleMenuOptions = computed(() => ({
  placement: "top",
  offset: 8,
  ...props.options,
}));

// shouldShow 回调
const shouldShowMenu = props.shouldShow || (({ from, to }: any) => from !== to);
</script>

<style lang="scss" scoped>
.bubble-menu-container {
  display: inline-flex;
  align-items: center;
  background: var(--editor-color-white);
  border: 1px solid var(--editor-border-color);
  border-radius: var(--editor-border-radius, 6px);
  box-shadow: var(--editor-shadow);
  padding: 2px;
  position: relative;
  z-index: 9999;
  pointer-events: auto;
}

/* 暗色主题 */
[theme-mode="dark"] {
  .bubble-menu-container {
    background: var(--editor-color-dark);
    border-color: var(--editor-border-color);
  }
}
</style>
